<template>
  <el-container>
    <el-main>
      <el-form ref="FormRef" :model="form" label-width="100px" show-message>
        <el-form-item :rules="{ required: true, message: '请输入账号', trigger: 'blur' }" label="账号：" prop="UserID">
          <el-input v-model="form.UserID" />
        </el-form-item>
        <el-form-item :rules="[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码不能小于6位大于18位' }
        ]" label="密码：" prop="Passwd">
          <el-input v-model="form.Passwd" type="password" show-password minlength="6" maxlength="18" />
        </el-form-item>

        <el-form-item :rules="{ required: true, message: '请输入用户名称', trigger: 'blur' }" label="用户名称：" prop="UserName">
          <el-input v-model="form.UserName" />
        </el-form-item>
        <el-form-item label="角色：" prop="UserRoles">
          <el-select v-model="form.UserRoles" placeholder="请选择角色" style="width: 100%" multiple>
            <el-option v-for="item in UserRoles" :value="item.RoleCode" :label="item.RoleName" :key="item.RoleCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话：" prop="TelNo">
          <el-input v-model="form.TelNo" />
        </el-form-item>
        <el-form-item label="邮箱：" prop="Email">
          <el-input v-model="form.Email" />
        </el-form-item>
        <el-form-item label="关联员工" prop="Email">
          <el-select v-model="selectMember" clearable placeholder="请选择">
            <el-option v-for="item in MemberList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item :rules="{
          required: true,
          message: '请选择状态',
          trigger: 'blur'
        }" label="状态：" prop="UserStatus">
          <el-select style="width: 100%" v-model="form.UserStatus" placeholder="请选择状态">
            <el-option label="正常" value="0" />
            <el-option label="暂停" value="3" />
            <el-option label="注销" value="9" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="submit(FormRef)" type="primary">提交</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>

<script lang="ts" setup>
// 机构添加用户
import type { FormInstance, FormRules } from 'element-plus'
import { httpReqeustApi } from '/@/api/linxyun/base';
import { ElMessage, ElMessageBox } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);
const emit = defineEmits(["close", "refresh"])




const FormRef = ref<FormInstance>()
const httpReqeust = httpReqeustApi();
const props = defineProps<{ UserRoles: any }>();
// const { UserRoles } = toRefs(props);
const form = reactive({
  UserID: '',
  Passwd: '',
  UserName: '',
  UserRoles: '',
  TelNo: '',
  Email: '',
  UserStatus: ''
})
const data = reactive({
  MemberList: [] as any[],
  selectMember: '',
})
const { MemberList, selectMember } = toRefs(data);

/**
 * @description: 提交
 */
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      sendRequest(form)

    } else {
      console.log('error submit!')
      return false
    }
  })
  cancel()
}

/**
 * @description: 发送请求新增
 */
const sendRequest = (param: any) => {
  const finallyParam = {
    UserID: param.UserID,
    Passwd: param.Passwd,
    UserName: param.UserName,
    TelNo: param.TelNo,
    Email: param.Email,
    UserStatus: param.UserStatus,
    CustomerType: 1,
    CustomerID: userInfos.value?.CustomerID,
    UserRoles: ''
  }
  let roles = ''
  if (form.UserRoles && form.UserRoles.length > 0) {
    for (let i = 0; i < form.UserRoles.length; i++) {
      if (i === 0) {
        roles = form.UserRoles[i]
      } else {
        roles += form.UserRoles[i]
      }
    }
  }
  finallyParam.UserRoles = roles
 
  httpReqeust.Post('addUser', finallyParam).then((result: any) => {
    if (result.msg === 'success' && result.code == '0000') {
      ElMessage({
        type: 'success',
        message: '添加成功',
      });
      // 修改用户的登录账户
      updateMemberInfo()
      emit('refresh')
    } else {
      ElMessage({
        type: 'error',
        message: '添加失败',
      });
    }
  }).catch((err) => {
    ElMessage({
      type: 'error',
      message: '添加失败',
    });
  });
}
/**
 * @description: 取消
 */
const cancel = () => {
  emit('close', false)
}

// 查询没有绑定账户的员工
const queryMember = () => { 
  httpReqeust.Post('QueryStaff').then((result: any) => {
    let Records = result.Records;
    for (let index = 0; index < Records.length; index++) {
      if (Records[index].LoginName == '') {
        MemberList.value.push({
          value: Records[index].MemberID,
          label: Records[index].UserName
        })
      }
    }
  })
}
queryMember()

// 修改用户信息
const updateMemberInfo=()=>{
  let param= {
    MemberID:selectMember.value,
    LoginName:form.UserID
  }
  console.log('param',param);
  
  httpReqeust.Post('update_tab_member',param).then((result: any) => {
    if (result.msg === 'success' && result.code == '0000') {
    } else {
      ElMessage({
        type: 'error',
        message: '修改用户信息失败',
      });
    }
  })
  
}
</script>
 